package com.fourth.app.dwd.log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fourth.utils.DateFormatUtil;
import com.fourth.utils.MyKafkaUtil;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

/**
 * @author wjy
 * @create 2022-08-19 16:56
 */
public class BaseLogApp {
    public static void main(String[] args) throws Exception {
        //1.创建执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        //1.1设置状态后端

        //2.读取topic_log主题数据创建流
        String topic = "topic_log";
        String groupId = "base_log_app0819";
        DataStreamSource<String> streamSource = env.addSource(MyKafkaUtil.getFlinkKafkaConsumer(topic, groupId));

        //3.将数据转为json对象
        SingleOutputStreamOperator<JSONObject> jsonObj = streamSource.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String value, Collector<JSONObject> out) throws Exception {
                try {
                    JSONObject jsonObject = JSON.parseObject(value);
                    out.collect(jsonObject);
                } catch (Exception ignored) {
                }
            }
        });

        //3.按照mid分组
        KeyedStream<JSONObject, String> keyedStream = jsonObj.keyBy(json -> json.getJSONObject("common").getString("mid"));

        //4.使用状态编程实现新老用户校验
        SingleOutputStreamOperator<JSONObject> checkIsNewDS = keyedStream.map(new RichMapFunction<JSONObject, JSONObject>() {
            //定义状态
            private ValueState<String> valueState;

            @Override
            public void open(Configuration parameters) throws Exception {
                //初始化状态
                valueState = getRuntimeContext().getState(new ValueStateDescriptor<String>("value-state", String.class));
            }
            @Override
            public JSONObject map(JSONObject value) throws Exception {
                //获取is_new标记,状态日期,当前数据中的日期
                String isNew = value.getJSONObject("common").getString("is_new");
                String lastDt = valueState.value();
                Long ts = value.getLong("ts");
                String curDt = DateFormatUtil.toDate(ts);
                //is_new为1，被系统判定为新用户，存在误判
                if ("1".equals(isNew)) {
                    if (lastDt == null) {
                        valueState.update(curDt);
                    } else if (!lastDt.equals(curDt)) {
                        value.getJSONObject("common").put("is_new","0");
                    }
                } else if (lastDt == null) {
                    //更新状态为昨日
                    valueState.update(DateFormatUtil.toDate(ts - 24 * 60 * 60 * 1000L));
                }
                return value;
            }
        });

        //5.使用侧输出流对日志数据做分流）---》分析日志间关系
        OutputTag<String> errorTag = new OutputTag<String>("error") {
        };
        OutputTag<String> startTag = new OutputTag<String>("start") {
        };
        OutputTag<String> displayTag = new OutputTag<String>("display") {
        };
        OutputTag<String> actionTag = new OutputTag<String>("action") {
        };
        OutputTag<String> videoTag = new OutputTag<String>("video") {
        };
        SingleOutputStreamOperator<String> pageDS = checkIsNewDS.process(new ProcessFunction<JSONObject, String>() {
            @Override
            public void processElement(JSONObject value, Context ctx, Collector<String> out) throws Exception {
                //尝试获取错误日志
                String err = value.getString("err");
                if (err != null) {
                    ctx.output(errorTag, err);
                    value.remove("err");
                }

                //尝试获取启动日志和播放日志
                String start = value.getString("start");
                String appVideo = value.getString("appVideo");
                if (start != null) {
                    ctx.output(startTag, start);
                    value.remove("start");
                } else if(appVideo != null){
                    ctx.output(videoTag,appVideo);
                    value.remove("appVideo");
                }else {
                    JSONObject common = value.getJSONObject("common");
                    JSONObject page = value.getJSONObject("page");
                    Long ts = value.getLong("ts");
                    //尝试获取曝光日志数据
                    JSONArray displays = value.getJSONArray("displays");
                    if (displays != null) {
                        for (int i = 0; i < displays.size(); i++) {
                            JSONObject display = displays.getJSONObject(i);
                            display.put("common", common);
                            display.put("page", page);
                            display.put("ts", ts);
                            ctx.output(displayTag, display.toJSONString());
                        }
                    }
                    //尝试获取曝光日志数据
                    JSONArray actions = value.getJSONArray("actions");
                    if (actions != null) {
                        for (int i = 0; i < actions.size(); i++) {
                            JSONObject action = actions.getJSONObject(i);
                            action.put("common", common);
                            action.put("page", page);
                            ctx.output(actionTag, action.toJSONString());
                        }
                    }

                    //移除行为和曝光数据
                    value.remove("displays");
                    value.remove("actions");

                    //输出页面日志数据
                    out.collect(value.toJSONString());
                }
            }
        });
        DataStream<String> errDS = pageDS.getSideOutput(errorTag);
        DataStream<String> videoDS = pageDS.getSideOutput(videoTag);
        DataStream<String> startDS = pageDS.getSideOutput(startTag);
        DataStream<String> displayDS = pageDS.getSideOutput(displayTag);
        DataStream<String> actionDS = pageDS.getSideOutput(actionTag);

        //打印测试
        pageDS.print("page>>>>>");
        errDS.print("errDS>>>>>");
        startDS.print("start>>>>>");
        displayDS.print("display>>>>>");
        actionDS.print("action>>>>>");
        videoDS.print("video>>>>>");


        String pageTopic = "dwd_traffic_page_log";
        String errTopic = "dwd_traffic_error_log";
        String startTopic = "dwd_traffic_start_log";
        String displayTopic = "dwd_traffic_display_log";
        String actionTopic = "dwd_traffic_action_log";
        String videoTopic = "dwd_traffic_action_log";

        //6.将数据写出到kafka
        pageDS.addSink(MyKafkaUtil.getFlinkKafkaProducer(pageTopic));
        errDS.addSink(MyKafkaUtil.getFlinkKafkaProducer(errTopic));
        startDS.addSink(MyKafkaUtil.getFlinkKafkaProducer(startTopic));
        displayDS.addSink(MyKafkaUtil.getFlinkKafkaProducer(displayTopic));
        actionDS.addSink(MyKafkaUtil.getFlinkKafkaProducer(actionTopic));
        videoDS.addSink(MyKafkaUtil.getFlinkKafkaProducer(videoTopic));

        //7.启动任务
        env.execute("BaseLogApp");
    }
}
